package ordersystem;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Order {
    private ArrayList<Dish> selectedDishes = new ArrayList<>();
    private Map<String, Integer> comboRecord = new HashMap<>();
    private double totalPrice = 0.0;
    // 双满减规则
    private static final double DISCOUNT_THRESHOLD1 = 29.99;
    private static final double DISCOUNT_AMOUNT1 = 5.0;
    private static final double DISCOUNT_THRESHOLD2 = 39.99;
    private static final double DISCOUNT_AMOUNT2 = 8.0;
    private static final double COMBO_DISCOUNT = 2.0;

    public void addSingleDish(Dish dish, int num) {
        for (int i = 0; i < num; i++) {
            selectedDishes.add(dish);
            totalPrice += dish.getPrice();
        }
        dish.reduceStock(num);
        System.out.println("  已添加" + dish.getName() + "x" + num);
    }

    public void calculateComboDiscount() {
        if (selectedDishes.size() < 2) return;

        Map<String, Integer> dishCount = new HashMap<>();
        for (Dish dish : selectedDishes) {
            dishCount.put(dish.getName(), dishCount.getOrDefault(dish.getName(), 0) + 1);
        }

        // 套餐逻辑（假设任意两种不同菜品可组合套餐）
        ArrayList<String> dishNames = new ArrayList<>(dishCount.keySet());
        for (int i = 0; i < dishNames.size(); i++) {
            for (int j = i + 1; j < dishNames.size(); j++) {
                String name1 = dishNames.get(i);
                String name2 = dishNames.get(j);
                int comboNum = Math.min(dishCount.get(name1), dishCount.get(name2));
                if (comboNum > 0) {
                    comboRecord.put(name1 + "+" + name2, comboNum);
                }
            }
        }
    }

    // 生成订单文本内容
    public String toText() {
        StringBuilder sb = new StringBuilder();
        sb.append("==================== 点餐小票 ====================\n");
        
        // 1. 套餐明细
        if (!comboRecord.isEmpty()) {
            sb.append("【套餐明细】\n");
            for (Map.Entry<String, Integer> entry : comboRecord.entrySet()) {
                String[] dishNames = entry.getKey().split("\\+");
                int num = entry.getValue();
                double singleComboOriginal = selectedDishes.stream()
                        .filter(d -> d.getName().equals(dishNames[0]))
                        .findFirst().get().getPrice() +
                        selectedDishes.stream()
                                .filter(d -> d.getName().equals(dishNames[1]))
                                .findFirst().get().getPrice();
                double singleComboPrice = singleComboOriginal - COMBO_DISCOUNT;
                sb.append("  ").append(dishNames[0]).append("+").append(dishNames[1])
                        .append(" | 原价").append(String.format("%.2f", singleComboOriginal))
                        .append("元 | 优惠价").append(String.format("%.2f", singleComboPrice))
                        .append("元 x").append(num).append("\n");
            }
        }

        // 2. 非套餐单品明细
        sb.append("\n【单品明细】\n");
        Map<String, Integer> comboUsed = new HashMap<>();
        for (Map.Entry<String, Integer> entry : comboRecord.entrySet()) {
            String[] dishNames = entry.getKey().split("\\+");
            comboUsed.put(dishNames[0], entry.getValue());
            comboUsed.put(dishNames[1], entry.getValue());
        }

        Map<String, Integer> remainingDish = new HashMap<>();
        for (Dish dish : selectedDishes) {
            remainingDish.put(dish.getName(), remainingDish.getOrDefault(dish.getName(), 0) + 1);
        }

        for (Map.Entry<String, Integer> used : comboUsed.entrySet()) {
            String dishName = used.getKey();
            int usedNum = used.getValue();
            remainingDish.put(dishName, remainingDish.get(dishName) - usedNum);
        }

        for (Map.Entry<String, Integer> entry : remainingDish.entrySet()) {
            String dishName = entry.getKey();
            int num = entry.getValue();
            if (num > 0) {
                double price = selectedDishes.stream()
                        .filter(d -> d.getName().equals(dishName))
                        .findFirst().get().getPrice();
                sb.append("  ").append(dishName).append(" | ").append(String.format("%.2f", price))
                        .append("元 x").append(num).append(" | 小计").append(String.format("%.2f", price * num)).append("元\n");
            }
        }

        // 3. 价格汇总
        double originalTotal = getOriginalTotal();
        sb.append("\n【价格汇总】\n");
        sb.append("  订单原价: ").append(String.format("%.2f", originalTotal)).append("元\n");

        if (!comboRecord.isEmpty()) {
            double totalComboDiscount = comboRecord.values().stream()
                    .mapToInt(Integer::intValue).sum() * COMBO_DISCOUNT;
            sb.append("  套餐优惠: -").append(String.format("%.2f", totalComboDiscount)).append("元\n");
        }

        double finalPrice = totalPrice;
        String discountDesc = "";
        if (totalPrice >= DISCOUNT_THRESHOLD2) {
            finalPrice -= DISCOUNT_AMOUNT2;
            discountDesc = "满39.99减8元";
        } else if (totalPrice >= DISCOUNT_THRESHOLD1) {
            finalPrice -= DISCOUNT_AMOUNT1;
            discountDesc = "满29.99减5元";
        } else {
            discountDesc = "无满减优惠";
        }
        sb.append("  满减优惠: ").append(discountDesc).append(" (").append(finalPrice >= totalPrice ? "+" : "-")
                .append(String.format("%.2f", Math.abs(finalPrice - totalPrice))).append("元)\n");
        sb.append("  最终应付: ").append(String.format("%.2f", finalPrice)).append("元\n");
        sb.append("==================================================\n");
        sb.append("  感谢点餐！超超超超级好吃快餐店 欢迎下次光临～\n");
        return sb.toString();
    }

    public void showOrder() {
        System.out.println(toText());
    }

    //获取订单原价
    public double getOriginalTotal() {
        return selectedDishes.stream().mapToDouble(Dish::getPrice).sum();
    }
}